<?php
namespace app\lib\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\Request;
use think\Log;
// use SeasLog;

class ApiExceptionHandle extends Handle
{
    private $statusCode = 500;
    private $message = '服务器错误!';
    private $errorCode = 999;

    /**
     * 异常处理接管
     */
    public function render(Exception $e)
    {
        // 如果调试模式，异常交由系统处理
        if(config('app_debug') == true){
            return parent::render($e);
        }

        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json($e->getError(), 422);
        }

        // 请求异常
        if ($e instanceof HttpException && request()->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }

        // 用户操作异常处理
        if ($e instanceof ApiException) {
            // $this->statusCode = $e->statusCode;
            // $this->message = $e->message;
            // $this->errorCode = $e->errorCode;
            // $this->recordErrorLog($e, 'ERROR', 'Api');
            return $this->apiError($e);
        } else {
            // $this->message = $this->getMessage($e);
            // $this->recordErrorLog($e, 'ERROR', 'Server');
            // $msg = '服务器出错！';
            return $this->serverError($e);
        }

        
        // $request = Request::instance();
        // $result = [
        //     'status' => $this->statusCode,
        //     'message' => $msg,
        //     'errorCode' => $this->errorCode,
        //     'requestUrl' => $request->url()
        // ];
        // return json($result, $this->httpCode);
    }

    public function apiError($e)
    {
        $this->statusCode = $e->statusCode;
        $this->message = $e->message;
        $this->errorCode = $e->errorCode;
        $this->level = $e->level;
        $data = [
            'file'    => $e->getFile(),
            'line'    => $e->getLine(),
            'message' => $this->message,
            'code'    => $this->statusCode,
            'module'  => 'Api'
        ];
        $log = "{$data['module']}[{$data['code']}][{$data['message']}][{$data['file']}:{$data['line']}]";
        $this->recordErrorLog($this->level, $log);
        $request = Request::instance();
        $result = [
            'status' => $this->statusCode,
            'message' => $this->message,
            'requestUrl' => $request->url()
        ];
        return json($result, $this->statusCode);
    }

    public function serverError($e)
    {
        $this->statusCode = $this->getCode($e);
        $this->message = $this->getMessage($e);
        $this->errorCode = 500;
        $data = [
            'file'    => $e->getFile(),
            'line'    => $e->getLine(),
            'message' => $this->message,
            'code'    => $this->statusCode,
            'module'  => 'Server'
        ];
        $log = "[{$data['module']}][{$data['code']}][{$data['message']}][{$data['file']}:{$data['line']}]";
        $this->recordErrorLog('ERROR', $log, 'Server');
        $request = Request::instance();
        $result = [
            'status' => $this->errorCode,
            'message' => '服务器出错！',
            'requestUrl' => $request->url()
        ];
        return json($result, $this->statusCode);
    }

    /**
     * 保存日志
     */
    private function recordErrorLog($level = 'debug', $log, $module = 'Server')
    {
        // Log::init([
        //     // 日志类型
        //     'type' => 'File',
        //     // 日志存储路径
        //     'path' => LOG_PATH,
        //     // 错误级别
        //     'level' => ['error']
        // ]);
        // $data = [
        //     'file'    => $e->getFile(),
        //     'line'    => $e->getLine(),
        //     'message' => $this->message,
        //     'code'    => $this->httpCode,
        // ];
        // $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]";
        // \SeasLog::log($level, $log, [], $module);
        Log::record($log, $level);
    }
}